<?php

class Proxy extends Base
{
    const MAX_USERS_PER_PROXY = 10;
    const TYPE_1_KEY = "75ce7769984add0d";

    function updateUserProxy(int $userId = 0, int $proxyId = 0, int $proxyType = 0)
    {
        if ($userId <= 0 || $proxyType < 1 || $proxyType > 2) return false;

        if ($proxyType == 2) {
            $this->mysql->table("proxy")("WHERE id = ?i", $proxyId)->update([
                'status' => 'disable',
            ]);
        }

        $day = date("Ymd");
        $excuteKey = "userExcute:{$day}:{$userId}";
        if (intval($this->rds->exists($excuteKey)) == 1) {
            //标记过期即可,等待程序自动切换
            $this->rds->hset($excuteKey, "proxy_expire_at", $this->currentTime - 1);
        }

        return true;
    }

    function get(int $type = 1, string $city = ""): array
    {
        if (!in_array($type, [1, 2])) {
            return [];
        }
        //1：小熊 2：鲸云
        if ($type == 1) {
            if (empty($city)) {
                $cond = [
                    "SELECT c.city,COUNT(*) AS total 
                    FROM `user` c
                    WHERE c.proxy_type = 1 AND c.proxy_id > 0 AND c.deleted_at IS NULL AND c.`status` = 'normal' 
                    GROUP BY c.city
                    ORDER BY total ASC",
                ];
                $proxyCitys = ($this->mysql)(...$cond)->all();
                $compareProxysCitys = [];
                foreach ($proxyCitys as $proxy) {
                    $compareProxysCitys[intval($proxy['city'])] = intval($proxy['total']);
                }
                $allCitys = require "littleBearCitys.php";
                $allCitys = array_map(function ($item) {
                    return 0;
                }, $allCitys);
                $allCitys = $compareProxysCitys + $allCitys;
                asort($allCitys);
                $city = array_key_first($allCitys);
            }

            //根据city提取IP
            // {"count":"1","status":"0","expire":"2025-09-14 13:12:14","list":[{"sever":"36.134.214.253","port":41065,"net_type":1}]}
            $proxyLink = sprintf("https://find.xiaoxiongip.com/find_s5?key=%s&count=1&type=json&only=1&city=%s&pw=no", self::TYPE_1_KEY, $city);
            $proxy = json_decode(file_get_contents($proxyLink), true);

            if (isset($proxy['status']) && intval($proxy['status']) === 0) {
                $item = $proxy['list'][0];
                return [
                    'id' => 0,
                    'ip' => $item['sever'],
                    'port' => $item['port'],
                    'type' => 1,
                    'user' => "",
                    'password' => "",
                    'expire_at' => trim($proxy['expire']),
                    'update_at' => date("Y-m-d H:i:s"),
                    'city' => $city,
                ];
            }
            return [];
        }

        if ($type == 2) {
            $cond = [
                "SELECT a.id,a.ip,a.port,a.user,a.password,a.update_at,a.expire_at,a.type,a.city,b.total
                FROM proxy a
                LEFT JOIN (
                    SELECT c.proxy_id,COUNT(*) AS total 
                    FROM `user` c
                    WHERE c.proxy_type = ?i AND c.proxy_id > 0 AND c.deleted_at IS NULL AND c.`status` = 'normal' 
                    GROUP BY c.proxy_id
                ) b
                ON a.id = b.`proxy_id`
                WHERE a.`deleted_at` IS NULL
                AND a.status = 'active'
                AND a.expire_at > ?s 
                AND (b.total <= ?i || b.total IS NULL) 
                ",
                $type,
                date("Y-m-d H:i:s"),
                self::MAX_USERS_PER_PROXY,
            ];
            if ($city) {
                $cond[0] .= " AND a.city = ?s ";
                $cond[] = $city;
            }
            $cond[0] .= "ORDER BY b.total ASC LIMIT 1";

            if ($proxy = ($this->mysql)(...$cond)->array()) {
                unset($proxy['total']);
                return $proxy;
            }
        }

        return [];
    }
}
